﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Sharp.DataTransferObject;
using Sharp.Infrastructure;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.Mvc;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;
// ReSharper disable Mvc.ViewNotResolved

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    [AutomaticTemplate]
    public class AvailablePermissionController : SharpController
    {
        // GET: Platform/AvailablePermission
        public async Task<ActionResult> Index()
        {
            Lazy<List<AvailablePermissionIndexViewModel>> newAvailablePermissionList =
                new Lazy<List<AvailablePermissionIndexViewModel>>();
            IEnumerable<PermissionDTO> list;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                list = await proxy.Channel.AllAvailablePermissions();
            }

            Build(list, newAvailablePermissionList.Value, null);

            return View(new AvailablePermissionIndexViewModel() { Data = newAvailablePermissionList.Value });
        }

        internal static void Build(IEnumerable<PermissionDTO> table, List<AvailablePermissionIndexViewModel> node,
            Guid? parentValue)
        {
            var rows = table.Where(x => x.ParentId == parentValue).OrderBy(x => x.SystemCode).ThenBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new AvailablePermissionIndexViewModel()
                {
                    Code = row.Code,
                    Category = row.Category,
                    Id = row.Id,
                    OrderIndex = row.OrderIndex,
                    ParentId = row.ParentId,
                    SystemCode = row.SystemCode,
                    Title = row.Title
                };


                if (row.ParentId == null)
                {
                    _node.Itemclass = $"treegrid-{row.Id}";
                }
                else
                {
                    _node.Itemclass = $"treegrid-{row.Id} treegrid-parent-{row.ParentId}";
                }


                node.Add(_node);

                Build(table, node, row.Id);
            }
        }

        public ActionResult SaveToPermission(Guid[] ids)
        {
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                var res = proxy.Channel.AvailablePermissionToPermission(ids);

                return this.JsonNet(res);
            }

        }
    }
}